package com.boarsoft.boar.sys.biz;

import java.util.List;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.sys.SysRoleFuncBiz;
import com.boarsoft.boar.sys.entity.RoleFunc;
import com.boarsoft.boar.sys.entity.SysFunc;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("sysRoleFuncBiz")
public class SysRoleFuncBizImpl extends SimpleBizImpl implements SysRoleFuncBiz {

	@Transactional(readOnly = true)
	public PagedResult<SysFunc> list(String roleId, String key, String orderBy, int pageNo, int pageSize) {
		StringBuffer sb = new StringBuffer();
		sb.append(" from ").append(SysFunc.class.getName());
		sb.append(" f join f.roles r where f.status=").append(SysFunc.STATUS_INUSE);
		if (Util.strIsNotEmpty(roleId)) {
			sb.append(" and r.id='").append(roleId).append("'");
		}
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (f.code like '%").append(key);
			sb.append("%' or f.name like '%").append(key);
			sb.append("%') ");
		}
		int total = Util.object2int(dao.getValue("select count(f.id)".concat(sb.toString())), 0);
		sb.append(" order by f.code");
		log.info(sb.toString());
		List<SysFunc> lt = dao.list("select f".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<SysFunc>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void toggle(String roleId, String[] funcs, boolean isAdd) {
		StringBuilder sb = new StringBuilder();
		sb.append("from ").append(RoleFunc.class.getName());
		sb.append(" where roleId=:roleId and funcCode=:fc");
		Query<RoleFunc> q = dao.createQuery(RoleFunc.class, sb.toString());
		for (String fc : funcs) {
			q.setParameter("roleId", roleId);
			q.setParameter("fc", fc);
			RoleFunc o = (RoleFunc) q.uniqueResult();
			if (o == null) {
				if (isAdd) {
					o = new RoleFunc();
					o.setFuncCode(fc);
					o.setRoleId(roleId);
					dao.save(o);
				}
			} else {
				dao.delete(o);
			}
		}
	}
}